﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using VehicleManagement.Models;
using VehicleManagement.Codes;
using VehicleManagement.ControllersServices;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;
using System.IO;
namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "负责人")]
    public class DriverController : Controller
    {
        const int PAGE_MAX = 8;
        //
        // GET: /Driver/
        DriverServices driverService = new DriverServices();
        public ActionResult Index()
        {

            Hashtable ht = new Hashtable();
            SearchDriverByRequeast(ref ht);
            int page;
            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
                page = int.Parse(Request.Params["Page"]);
            else
                page = 1;
            return View(driverService.SearchAllDriver(ht, (page - 1) * PAGE_MAX, PAGE_MAX));

            //return View(driverService.GetAllDriver());//返回所有司机的简要简要信息列表的视图

        }

        /// <summary>
        /// 添加司机
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            return View();

        }
        [HttpPost]
        public ActionResult Create(DriverInfo driver)
        {
            if (Session["CompanyName"] == null)
            {
                return View("../Home/Login");
            }
            if (ModelState.IsValid)
            {
                driver.CompanyName = Session["CompanyName"].ToString();
                Object thisLock = new Object();
                int id = 0;
                lock (thisLock)
                {
                    object obj = driverService.CreateDriver(driver);
                    id = (int)SqlMapperManager.Instance.Get().QueryForObject("SELECT_DRIVER_IDENTITY", null);
                }
                HttpPostedFileBase file = Request.Files["file"];
                if (file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/Driver") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_DRIVER_HEAD_IMAGE",
                        new
                        {
                            DriverID = id,
                            Image = id + fileExt
                        });
                }
                return RedirectToAction("Index");
            }
            else
                return View(driver);
        }

        /// <summary>
        /// 根据司机ID，查看司机详细信息，并返回视图
        /// </summary>
        /// <param name="id">司机的ID</param>
        /// <returns>司机信息详细视图</returns>
        public ActionResult Details(int id)
        {
            return View(driverService.GetDriverByDriverID(id));
        }


        /// <summary>
        /// 司机信息修改
        /// </summary>
        /// <param name="id">司机ID</param>
        /// <param name="driveriofo">返回司机类</param>
        /// <returns>修改司机的视图</returns>
        public ActionResult Edit(int id)
        {
            DriverInfo driverInfo = driverService.GetDriverByDriverID(id);
            return View(driverInfo);
        }
        [HttpPost]
        public ActionResult Edit(DriverInfo driveriofo)
        {
            //  if (ModelState.IsValid)
            // {
            int rows = driverService.EditDriver(driveriofo);
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null && file.ContentLength > 0)
            {
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                file.SaveAs(Server.MapPath("~/Photos/Driver") + @"\" + driveriofo.DriverID + fileExt);
                SqlMapperManager.Instance.Get().Update("UPDATE_DRIVER_HEAD_IMAGE",
                    new
                    {
                        DriverID = driveriofo.DriverID,
                        Image = driveriofo.DriverID + fileExt
                    });
            }
            if (rows == 1)
            {
                return RedirectToAction("Index");
            }
            // }
            else
                return View(driveriofo);

        }

        /// <summary>
        /// 根据司机的ID，删除司机
        /// </summary>
        /// <param name="id">司机ID</param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            DriverInfo diverInfo = driverService.GetDriverByDriverID(id);
            return View(diverInfo);
        }
        /// <summary>
        /// 删除司机
        /// </summary>
        /// <param name="id">司机ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (Request.IsAjaxRequest())
            {
                int i = driverService.DeleteDriver(id);//根据司机ID，删除
                if (i == 1)//删除成功
                {
                    return Json(new { Result = "true", Message = "删除成功" });
                }
                else//删除不成功
                {
                    return Json(new { Result = "false", Message = "删除失败" });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "该方法只能通过AJAX方式调用" });
            }

        }


        /// <summary>
        /// 获取司机信息(如管理员个人中心)
        /// </summary>
        /// <returns>个人中心的视图</returns>
        public ActionResult MyInformation()
        {
            if (Session["UserID"] == null)
                Response.Redirect("/Home/Login");
            int id = Convert.ToInt32(Session["UserID"]);
            return View(driverService.GetDriverByDriverID(id));
        }


        //获取对应公司所有司机姓名
        // POST: /Driver/GetDriverNameList
        [HttpPost, ActionName("GetDriverNameList")]
        public ActionResult GetDriverNameList()
        {
            string companyName = Session["CompanyName"].ToString();
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_DRIVERNAME", companyName);
            return Json(list);
        }

        //获取（公司）状态为空闲的司机姓名
        // POST: /Driver/GetDriverNameListByState
        [HttpPost, ActionName("GetDriverNameListByState")]
        public ActionResult GetDriverNameListByState(int state)
        {
            Hashtable ht = new Hashtable();
            string companyName = "%%";
            if (Session["CompanyName"].ToString() != null)
            {
                companyName = Session["CompanyName"].ToString();
            }
            ht.Add("state", state);
            ht.Add("companyName", companyName);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_DriverName_BY_Free", ht);
            return Json(list);
        }

        [ActionName("GetPagingInfo"), HttpGet]
        public ActionResult GetPagingInfo()
        {
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);

            Hashtable ht = new Hashtable();
            SearchDriverByRequeast(ref ht);
            int itemCount = driverService.CountAllDrivers(ht);
            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 搜索司机
        /// </summary>
        /// <param name="ht">构造查询条件（哈希表实现）</param>
        [NonAction]
        private void SearchDriverByRequeast(ref Hashtable ht)
        {

            string driverState = Request.Params["DriverState"];
            string driverName = Request.Params["DriverName"];
            string sex = Request.Params["Sex"];
            string driverNameForSearch = "%%";
            //string linceTypeForSearch = "%%";
            string sexForSearch = "%%";
            string companyName = "%%";
            int driverStateForSearch = 3;

            if (Session["CompanyName"].ToString() != null)
            {
                companyName = Session["CompanyName"].ToString();
            }

            if (driverState == "空闲")
                driverStateForSearch = 0;
            else if (driverState == "忙碌")
                driverStateForSearch = 1;

            if (!string.IsNullOrEmpty(driverName) && driverName != "姓名")
                driverNameForSearch = string.Format("%{0}%", driverName);
            if (!string.IsNullOrEmpty(sex))
                sexForSearch = string.Format("%{0}%", sex);

            ht.Add("driverNameForSearch", driverNameForSearch);
            ht.Add("driverStateForSearch", driverStateForSearch);
            //ht.Add("linceTypeForSearch", linceTypeForSearch);
            ht.Add("sexForSearch", sexForSearch);
            ht.Add("companyName", companyName);
        }

        /// <summary>
        /// 增加的司机时，远程验证司机姓名不能重复。
        /// </summary>
        /// <param name="DriverName">司机的姓名</param>
        /// <returns>Json字符串提醒</returns>
        [HttpGet]
        public ActionResult CheckUserAccountExists(DriverInfo driver)
        {
            Hashtable ht = new Hashtable();
            string companyName = Session["CompanyName"].ToString();
            ht.Add("companyName", companyName);
            ht.Add("driverID", driver.DriverID);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_DRIVER_CHECK", ht);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == driver.DriverName.ToLower())) == false;
            return Json(!exists, JsonRequestBehavior.AllowGet);


        }
        /// <summary>
        /// 增加的司机时，远程验证邮箱不能重复。
        /// </summary>
        /// <param name="DriverName">司机对象</param>
        /// <returns>Json字符串提醒</returns>
        [HttpGet]
        public ActionResult CheckEmailExists(DriverInfo driver)
        {
            Hashtable ht = new Hashtable();
            string companyName = Session["CompanyName"].ToString();
            ht.Add("companyName", companyName);
            ht.Add("driverID", driver.DriverID);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_EMAIL_CHECK", ht);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == driver.Email.ToLower())) == false;
            return Json(!exists, JsonRequestBehavior.AllowGet);


        }
         /// <summary>
        /// 增加的司机时，远程验证手机号码不能重复。
        /// </summary>
        /// <param name="DriverName">司机对象</param>
        /// <returns>Json字符串提醒</returns>
        [HttpGet]
        public ActionResult CheckTelephoneExists(DriverInfo driver)
        {
            Hashtable ht = new Hashtable();
            string companyName = Session["CompanyName"].ToString();
            ht.Add("companyName", companyName);
            ht.Add("driverID", driver.DriverID);
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_ALL_Telephone_CHECK", ht);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == driver.Telephone.ToLower())) == false;
            return Json(!exists, JsonRequestBehavior.AllowGet);


        }
        


    }
}
